<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>客户管理系统</title>
    <!-- 引入Vue 2 -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <!-- 引入Element UI -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- 引入axios -->
    <script src="../../plugins/axios/axios.min.js"></script>
    <style>
        .app-container {
            padding: 20px;
        }
        .pagination-container {
            margin-top: 20px;
            text-align: right;
        }
        .clearfix:before,
        .clearfix:after {
            display: table;
            content: "";
        }
        .clearfix:after {
            clear: both;
        }
        .el-table {
            margin-top: 15px;
        }
    </style>
</head>
<body>
<div id="app">
    <div class="app-container">
        <el-card>
            <!-- 搜索和操作区域 -->
            <div slot="header" class="clearfix">
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-input
                                v-model="searchQuery"
                                placeholder="输入客户名称搜索"
                                clearable
                                @clear="handleSearch"
                                @keyup.enter.native="handleSearch"
                        >
                            <el-button slot="append" icon="el-icon-search" @click="handleSearch" />
                        </el-input>
                    </el-col>
                    <el-col :span="16" style="text-align: right">
                        <el-button type="primary" @click="handleCreate">
                            <i class="el-icon-plus"></i> 新增客户
                        </el-button>
                    </el-col>
                </el-row>
            </div>
<!--            <el-table-->
<!--                    :data="customerList"-->
<!--                    border-->
<!--                    style="width: 100%"-->
<!--                    v-loading="loading"-->
<!--                    @sort-change="handleSortChange"-->
<!--            >-->
<!--                <el-table-column prop="customerId" label="ID" width="80" sortable="custom" />-->
<!--                <el-table-column prop="name" label="客户名称" min-width="150" />-->
<!--                <el-table-column prop="contactPerson" label="联系人" width="120" />-->
<!--                <el-table-column prop="contactEmail" label="联系邮箱" width="180">-->
<!--                    <template slot-scope="scope">-->
<!--                        <a :href="`mailto:${scope.row.contactEmail}`">{{ scope.row.contactEmail }}</a>-->
<!--                    </template>-->
<!--                </el-table-column>-->
<!--                <el-table-column prop="contactPhone" label="联系电话" width="130" />-->
<!--                <el-table-column prop="address" label="地址" min-width="200" show-overflow-tooltip />-->
<!--                <el-table-column label="操作" width="180" fixed="right">-->
<!--                    <template slot-scope="scope">-->
<!--                        <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>-->
<!--                        <el-button-->
<!--                                size="mini"-->
<!--                                type="danger"-->
<!--                                @click="handleDelete(scope.row.customerId)"-->
<!--                        >删除</el-button>-->
<!--                    </template>-->
<!--                </el-table-column>-->
<!--            </el-table>-->
            <el-table
                    ref="multipleTable"
                    :data="customerList"
                    v-loading="loading"
                    tooltip-effect="dark"
                    style="width: 100%"
                    @selection-change="handleSortChange">
                <el-table-column
                        type="selection"
                        width="55">
                </el-table-column>
                <el-table-column
                        prop="name"
                        label="客户名称"
                        width="150">
                </el-table-column>
                <el-table-column
                        prop="contactPerson"
                        label="联系人"
                        show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                        prop="contactEmail"
                        label="联系邮箱"
                        show-overflow-tooltip>
                    <template slot-scope="scope">-->
                        <a :href="`mailto:${scope.row.contactEmail}`">{{ scope.row.contactEmail }}</a>-->
                    </template>
                </el-table-column>
                <el-table-column
                        prop="contactPhone"
                        label="联系电话"
                        show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                        prop="address"
                        label="地址"
                        show-overflow-tooltip>
                </el-table-column>

                <el-table-column label="操作" width="180"  fixed="right">
                    <template slot-scope="scope">
                        <el-button
                            size="mini"
                            type="danger"
                            @click="handleDelete(scope.row.customerId)"
                            >删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页控件 -->
            <div class="pagination-container">
                <el-pagination
                        :current-page="pagination.currentPage"
                        :page-sizes="[10, 20, 30, 50]"
                        :page-size="pagination.pageSize"
                        :total="pagination.total"
                        layout="total, sizes, prev, pager, next, jumper"
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                />
            </div>
        </el-card>

        <!-- 新增/编辑对话框 -->
        <el-dialog
                :title="dialogTitle"
                :visible.sync="dialogVisible"
                width="50%"
                @close="resetForm"
        >
            <el-form
                    ref="customerForm"
                    :model="form"
                    :rules="rules"
                    label-width="100px"
            >
                <el-form-item label="客户名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入客户名称" />
                </el-form-item>
                <el-form-item label="联系人" prop="contactPerson">
                    <el-input v-model="form.contactPerson" placeholder="请输入联系人" />
                </el-form-item>
                <el-form-item label="联系邮箱" prop="contactEmail">
                    <el-input v-model="form.contactEmail" placeholder="请输入联系邮箱" />
                </el-form-item>
                <el-form-item label="联系电话" prop="contactPhone">
                    <el-input v-model="form.contactPhone" placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input
                            v-model="form.address"
                            type="textarea"
                            :rows="2"
                            placeholder="请输入详细地址"
                    />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</div>
<script>
    // 配置axios基础URL和拦截器
    axios.defaults.baseURL = 'http://localhost:8080'; // 替换为你的API基础URL

    // 请求拦截器
    axios.interceptors.request.use(config => {
        // 可以在这里添加token等请求头
        // config.headers.Authorization = 'Bearer ' + localStorage.getItem('token');
        return config;
    }, error => {
        return Promise.reject(error);
    });

    // 响应拦截器
    axios.interceptors.response.use(response => {
        return response.data;
    }, error => {
        console.error('API请求错误:', error);
        return Promise.reject(error);
    });

    // API方法
    const api = {
        getCustomers(params) {
            return axios.get('/api/customers', { params });
        },
        createCustomer(data) {
            return axios.post('/api/customers', data);
        },
        updateCustomer(data) {
            return axios.put(`/api/customers/${data.customerId}`, data);
        },
        deleteCustomer(id) {
            return axios.delete(`/api/customers/${id}`);
        }
    };

    new Vue({
        el: '#app',
        data() {
            return {
                // 搜索条件
                searchQuery: '',
                // 排序字段
                sortField: '',
                sortOrder: '',

                // 加载状态
                loading: false,

                // 客户列表数据
                customerList: [],

                // 分页配置
                pagination: {
                    currentPage: 1,
                    pageSize: 10,
                    total: 0
                },

                // 对话框配置
                dialogVisible: false,
                dialogTitle: '',
                isEdit: false,

                // 表单数据
                form: {
                    customerId: null,
                    name: '',
                    contactPerson: '',
                    contactEmail: '',
                    contactPhone: '',
                    address: ''
                },

                // 表单验证规则
                rules: {
                    name: [
                        { required: true, message: '请输入客户名称', trigger: 'blur' },
                        { min: 2, max: 100, message: '长度在 2 到 100 个字符', trigger: 'blur' }
                    ],
                    contactPerson: [
                        { required: true, message: '请输入联系人', trigger: 'blur' }
                    ],
                    contactEmail: [
                        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
                    ],
                    contactPhone: [
                        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
                    ],
                    address: [
                        { required: true, message: '请输入地址', trigger: 'blur' }
                    ]
                }
            }
        },
        created() {
            this.fetchData();
        },
        methods: {
            // 获取客户数据
            fetchData() {
                this.loading = true;
                const params = {
                    page: this.pagination.currentPage,
                    pageSize: this.pagination.pageSize,
                    name: this.searchQuery,
                    // sortField: this.sortField,
                    // sortOrder: this.sortOrder
                };

                api.getCustomers(params)
                    .then(response => {
                        // 直接使用response.list而不是response.data.list
                        this.customerList = response.list || [];
                        this.pagination.total = response.total || 0;
                    })
                    .catch(error => {
                        console.error('获取客户数据失败:', error);
                        this.$message.error('获取客户数据失败');
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },

            // 处理搜索
            handleSearch() {
                this.pagination.currentPage = 1;
                this.fetchData();
            },

            // 处理排序
            handleSortChange({ column, prop, order }) {
                this.sortField = prop || '';
                this.sortOrder = order === 'ascending' ? 'asc' : order === 'descending' ? 'desc' : '';
                this.fetchData();
            },

            // 处理分页大小变化
            handleSizeChange(val) {
                this.pagination.pageSize = val;
                this.fetchData();
            },

            // 处理当前页变化
            handleCurrentChange(val) {
                this.pagination.currentPage = val;
                this.fetchData();
            },

            // 打开新增对话框
            handleCreate() {
                this.dialogTitle = '新增客户';
                this.isEdit = false;
                this.dialogVisible = true;
            },

            // 打开编辑对话框
            handleEdit(row) {
                this.dialogTitle = '编辑客户';
                this.isEdit = true;
                this.form = Object.assign({}, row);
                this.dialogVisible = true;
            },

            // 提交表单
            submitForm() {
                this.$refs.customerForm.validate(valid => {
                    if (valid) {
                        const action = this.isEdit ? api.updateCustomer : api.createCustomer;
                        const successMsg = this.isEdit ? '更新成功' : '创建成功';

                        action(this.form)
                            .then(() => {
                                this.$message.success(successMsg);
                                this.dialogVisible = false;
                                this.fetchData();
                            })
                            .catch(error => {
                                console.error('操作失败:', error);
                                this.$message.error('操作失败');
                            });
                    } else {
                        return false;
                    }
                });
            },

            // 删除客户
            handleDelete(id) {
                this.$confirm('确定要删除该客户吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        api.deleteCustomer(id)
                            .then(() => {
                                this.$message.success('删除成功');
                                this.fetchData();
                            })
                            .catch(error => {
                                console.error('删除失败:', error);
                                this.$message.error('删除失败');
                            });
                    })
                    .catch(() => {
                        this.$message.info('已取消删除');
                    });
            },

            // 重置表单
            resetForm() {
                this.$refs.customerForm.resetFields();
                this.form = {
                    customerId: null,
                    name: '',
                    contactPerson: '',
                    contactEmail: '',
                    contactPhone: '',
                    address: ''
                };
            }
        }
    });
</script>
</body>
</html>